Exception Handling

1. Exception Handling in Java

Exception Class

The Exception class is the base class for all exceptions in Java. All custom exceptions should inherit from this class. Examples include:

Types of Exceptions

Checked Exceptions: Exceptions checked at compile-time, such as IOException and SQLException. These must be handled using try-catch or declared using throws.

Unchecked Exceptions: Exceptions that occur at runtime, like NullPointerException and ArithmeticException. These are subclasses of RuntimeException.

Exception Handling Keywords

User-defined Exceptions

Custom exceptions can be created by extending the Exception class.

    
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
    

    

Example Code Demonstrating Exception Handling


import java.io.*;

class TestExceptionHandling {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("Caught Arithmetic Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}


    

2. Viva/Interview Questions

An exception is an unexpected event that disrupts the normal flow of a program's instructions. Java provides various mechanisms to handle these exceptions.
Checked Exceptions: Exceptions that are checked at compile-time (e.g., IOException, SQLException).
Unchecked Exceptions: Exceptions that are not checked at compile-time (e.g., NullPointerException, ArithmeticException).
User-defined exceptions are custom exceptions created by the programmer by extending the Exception class.
try: The block of code that may throw an exception.
catch: Handles the exception thrown by the try block.
throw: Used to explicitly throw an exception.
throws: Declares exceptions that can be thrown by a method.
finally: Executes important code after the try-catch block, regardless of exception occurrence.
No, the finally block is always executed unless the program terminates using System.exit().
throw: Used to explicitly throw an exception within a method.
throws: Used in method declaration to specify the exceptions a method can throw.